import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import loginAPI from '@/apis/authAPI/loginAPI'
import logoutAPI from '@/apis/authAPI/logoutAPI'
import getPersonalInfoAPI from '@/apis/authAPI/getPersonalInfoAPI'

// 全局状态
const isAuthenticated = ref(false)
const currentUser = ref<any>(null)
const userRole = ref<'teacher' | 'student' | null>(null)
const token = ref<string | null>(null)

export const useAuth = () => {
  const router = useRouter()

  // 检查本地存储中的认证状态
  const checkAuthStatus = () => {
    const storedToken = localStorage.getItem('token')
    const storedRole = localStorage.getItem('role')
    const storedUser = localStorage.getItem('userInfo')
    
    if (storedToken) {
      token.value = storedToken
      isAuthenticated.value = true
      
      // 优先使用直接存储的 role，然后从 userInfo 中获取
      let role = storedRole
      if (!role && storedUser) {
        const userInfo = JSON.parse(storedUser)
        role = userInfo.role
        currentUser.value = userInfo
      }
      
      // 处理不同的角色格式
      if (role) {
        // 处理大小写和不同的角色标识
        const normalizedRole = role.toLowerCase()
        if (normalizedRole === 'teacher' || normalizedRole === 'TEACHER') {
          userRole.value = 'teacher'
        } else if (normalizedRole === 'student' || normalizedRole === 'STUDENT') {
          userRole.value = 'student'
        } else {
          // 默认为学生
          userRole.value = 'student'
        }
      } else {
        // 如果没有角色信息，默认为学生
        userRole.value = 'student'
      }
      
      console.log('认证状态检查完成:', { 
        token: !!storedToken, 
        role: userRole.value, 
        rawRole: role 
      })
    } else {
      // 清除所有状态
      isAuthenticated.value = false
      currentUser.value = null
      userRole.value = null
      token.value = null
    }
  }

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const response = await loginAPI({ username, password })
      
      if (response.code === 200) {
        // 保存token
        const authToken = response.data.token || response.data.access_token
        localStorage.setItem('id', response.data.user.id)
        localStorage.setItem('role', response.data.user.role)
        localStorage.setItem('email', response.data.email)
        if (authToken) {
          token.value = authToken
          localStorage.setItem('token', authToken)
        }
        
        // 获取用户信息
        await fetchUserInfo()
        return { success: true, message: '登录成功' }
      } else {
        return { success: false, message: response.message || '登录失败' }
      }
    } catch (error: any) {
      console.error('登录错误:', error)
      return { success: false, message: error.message || '登录失败' }
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response: any = await getPersonalInfoAPI()
      
      if (response.code === 200) {
        currentUser.value = response.data
        userRole.value = response.data.role === 'teacher' ? 'teacher' : 'student'
        isAuthenticated.value = true
        
        // 保存到本地存储
        localStorage.setItem('userInfo', JSON.stringify(response.data))
        
        return response.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，清除认证状态
      logout()
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      // 调用退出登录API
      await logoutAPI()
    } catch (error) {
      console.error('退出登录API调用失败:', error)
    } finally {
      // 清除本地状态
      isAuthenticated.value = false
      currentUser.value = null
      userRole.value = null
      token.value = null
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 重定向到登录页
      router.push('/login')
    }
  }

  // 检查权限
  const hasPermission = (requiredRole: string | string[]) => {
    if (!isAuthenticated.value || !userRole.value) {
      return false
    }
    
    if (Array.isArray(requiredRole)) {
      return requiredRole.includes(userRole.value)
    }
    
    return userRole.value === requiredRole
  }

  // 获取用户主页路由
  const getUserHomePage = () => {
    if (!userRole.value) return '/login'
    return userRole.value === 'teacher' ? '/teacher-home' : '/student-home'
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      // 这里可以调用刷新token的API
      // const response = await refreshTokenAPI()
      // 暂时返回false，表示需要重新登录
      return false
    } catch (error) {
      console.error('刷新token失败:', error)
      return false
    }
  }

  // 初始化时检查认证状态
  checkAuthStatus()

  return {
    // 状态
    isAuthenticated: computed(() => isAuthenticated.value),
    currentUser: computed(() => currentUser.value),
    userRole: computed(() => userRole.value),
    token: computed(() => token.value),
    
    // 方法
    login,
    logout,
    fetchUserInfo,
    hasPermission,
    getUserHomePage,
    refreshToken,
    checkAuthStatus
  }
}
